import { Component, ViewChild, Host, ChangeDetectionStrategy, ChangeDetectorRef } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { CompanyEsgService } from '../companyEsg.service';
import { AppComponent } from '../../../../../app.component';
import { Subscription, ReplaySubject } from 'rxjs';
import { CompanyModel } from '../../company.model';
import { CompanyService } from '../../company.service';
import { EsgKeyIssueValue } from './models/EsgKeyIssueValue.model';
import { EsgOverallAssessment } from './models/EsgOverallAssessment.model';
import { EsgKeyIssueIndicator } from './models/EsgKeyIssueIndicator.model';
import { EsgKeyIssueAssessment } from './models/EsgKeyIssueAssessment.model';
import { ResearchState } from '../../../research.service';
import * as _ from 'lodash';
import { EsgIndicatorsGrouped } from './models/esgIndicatorsGrouped.component';
import { ModalComponent } from '../../../../../shared/components/modal/modal.component';
import { IssueType } from '../../../../../shared/models/issue.enum';
import { AnalyticsService } from '../../../../../shared/services/googleAnalytics.service';
import { GoogleAnalyticsBeacon } from '../../../../../shared/models/googleAnalytics.model';

/**
 * Company ESG Analyst View component
 *
 * Author: Andrei Istrate
 * Date: 23.02.2018
 */
@Component({
  templateUrl: './esgAnalystView.component.html',
  styleUrls: ['../../company.component.scss'],
  changeDetection: ChangeDetectionStrategy.OnPush
})
export class CompanyESGAnalystViewComponent {
  public company: CompanyModel;
  private sub: Subscription;
  private environmentSub: Subscription;
  private socialSub: Subscription;
  private governanceSub: Subscription;
  private modalSub: Subscription;
  private environmentDetails = new ReplaySubject<any[]>(1);
  private socialDetails = new ReplaySubject<any[]>(1);
  private governanceDetails = new ReplaySubject<any[]>(1);


  public esgKeyIssueValue: EsgKeyIssueValue[];
  public esgOverallAssessment: EsgOverallAssessment;

  public esgGroupedIndicators: EsgIndicatorsGrouped[]//EsgKeyIssueIndicator[];

  public esgKeyIssueAssessment: EsgKeyIssueAssessment[];
  public matrixData: any[];
  public companyLetters: string[] = [];
  public researchState = ResearchState;
  public commentaryForIssue;
  public researchType;
  public selectedItem;
  public selectedIndicator;

  @ViewChild('itemDetails') itemDetails: ModalComponent;
  @ViewChild('issueDetails') issueDetails: ModalComponent;

  constructor(
    @Host() private rootComponent: AppComponent,
    private cdRef: ChangeDetectorRef,
    private companyService: CompanyService,
    private companyEsgService: CompanyEsgService,
    private analyticsService: AnalyticsService,
    private http: HttpClient) { }

  ngOnInit() {
    this.commentaryForIssue = {};
    this.sub = this.companyService.company.subscribe(data => {
      this.company = data;
      this.analyticsService.sendBeacon(new GoogleAnalyticsBeacon('ESGRatingAnalystView', 'Research', { CompanyId: this.company.id }));
      this.researchType = data.comprehensiveEsgResearchState === ResearchState.ResearchAvailable ? 'comprehensive' : 'core';

      this.companyEsgService.getEsgKeyIssueValue(this.company.id).subscribe(data => {
        this.esgKeyIssueValue = data;
        this.cdRef.markForCheck();
        let letterCode: number = 65;

        this.matrixData = this.esgKeyIssueValue.map(esgKeyIssueValue => {
          return {
            X: esgKeyIssueValue.keyEsgIssue.selected ? esgKeyIssueValue.businessImpact : undefined,
            Y: esgKeyIssueValue.keyEsgIssue.selected ? esgKeyIssueValue.sustainabilityImpact : undefined,
            currentX: !esgKeyIssueValue.keyEsgIssue.selected ? esgKeyIssueValue.businessImpact : undefined,
            currentY: !esgKeyIssueValue.keyEsgIssue.selected ? esgKeyIssueValue.sustainabilityImpact : undefined,
            description: this.companyLetters[this.companyLetters.push(String.fromCharCode(letterCode++)) - 1]
          };
        });
        this.cdRef.markForCheck();
      });


      this.companyEsgService.getEsgOverallAssessment(this.company.id).subscribe(data => {
        this.esgOverallAssessment = data;
        this.cdRef.markForCheck();
      });

      this.companyEsgService.getEsgKeyIssueIndicator(this.company.id).subscribe(data => {
        this.esgGroupedIndicators = _(data).groupBy('keyEsgIssue.name').map(function (items, key) {
          return new EsgIndicatorsGrouped(items[0].keyEsgIssue.name, items);
        }).value();

        this.cdRef.markForCheck();
      });

      this.companyEsgService.getEsgKeyIssueAssessment(this.company.id).subscribe(data => {
        data.forEach(x => this.commentaryForIssue[x.keyEsgIssue.name] = x.assessmentText);
        this.cdRef.markForCheck();
      });

      this.rootComponent.finishLoading();

      //get indicator details ready
      //TODO: create back-end call. Or just use tehse instead of getEsgKeyIssueIndicator
      this.environmentSub = this.companyEsgService.getEsgCompanyRpIndicator(this.company.id, IssueType.Environment, '').subscribe(data => {
        this.environmentDetails.next(data);
      });

      this.socialSub = this.companyEsgService.getEsgCompanyRpIndicator(this.company.id, IssueType.Social, '').subscribe(data => {
        this.socialDetails.next(data);
      });

      this.governanceSub = this.companyEsgService.getEsgCompanyRpIndicator(this.company.id, IssueType.Governance, '').subscribe(data => {
        this.governanceDetails.next(data);        
      });
    });
  }

  ngOnDestroy() {
    this.sub.unsubscribe();
    this.environmentSub.unsubscribe();
    this.socialSub.unsubscribe();
    this.governanceSub.unsubscribe();
    if(this.modalSub) this.modalSub.unsubscribe();

    this.environmentDetails.unsubscribe();
    this.socialDetails.unsubscribe();
    this.governanceDetails.unsubscribe();
  }

  /**
   * Get best practice gap
   * @param indicator Provided indicator
   */
  public getGap(indicator: EsgKeyIssueIndicator): number {
    return indicator.isEventIndicator ?
      indicator.eventIndicatorScore.materialBestPracticeGap :
      indicator.rpIndicatorScore.materialBestPracticeGap;
  }

  public showItemDetails(item: EsgKeyIssueValue) {
    this.selectedItem = item;
    if (this.commentaryForIssue[item.keyEsgIssue.name] && this.commentaryForIssue[item.keyEsgIssue.name].length > 0)
      this.itemDetails.show();
  }

  public tickboxGroups: any[];
  public showIssueDetails(indicator: EsgKeyIssueIndicator) {
    if(!indicator.isEventIndicator)
    {
      let subscription: ReplaySubject<any[]>;
      switch(IssueType[indicator.indicatorTheme]){
        case IssueType.Environment: 
          subscription = this.environmentDetails;
          break;
        case IssueType.Social: 
          subscription = this.socialDetails;
          break;
        case IssueType.Governance: 
          subscription = this.governanceDetails;
          break;
      }

      this.modalSub = subscription.subscribe(data => {
        this.selectedIndicator = data.find(x => x.code == indicator.number);
        let numCheckboxes = this.selectedIndicator.ticboxes.length;
        this.tickboxGroups = _.chunk(this.selectedIndicator.ticboxes, (numCheckboxes > 4 ? Math.ceil(numCheckboxes / 2) : numCheckboxes));                
        this.cdRef.markForCheck();
        this.issueDetails.show();
      });    
    }
  }
}